// user functions - - - - - - - - - - - - - - - - - - - -


// pre-load initializaton
chess_spider.tasks.init = function() {

	// if already initialized done
	if( this.initialized ) return;

	// make sure not ready for user
	chess_spider.state.ready = true;

	// initialize messaging
	if( chess_spider.params.control.messaging ) chess_spider.Message.init();

	// initialize stores 
	chess_spider.stores.initall();

	// keystrokes
	if( chess_spider.params.control.keystrokes ) window.addEventListener('keydown',chess_spider.events.keyDown,true);

	// onload
	if( !chess_spider.state.onloadInitialized ) window.addEventListener('load',onloadInit,true);

	// reposition
	window.addEventListener('resize',reposition,true);

	// find our pgn - - - - - - - - - - - - - - - - - - - -
	
	// as constant
	if( chess_spider.params.pgn ) null;
	
	// as string inside dummy script
	else if( document.getElementById('cs__pgn') ) chess_spider.params.pgn = document.getElementById('cs__pgn').innerHTML;

	// pgn_url as cs parameter - return since callback will parse
	else if( chess_spider.params.pgn_url ) {
		// todo: put this as a proper call
		if( chess_spider.params.control.messaging ) chess_spider.tasks.loadPgnSubmit( chess_spider.params.pgn_url );
		else chess_spider.loadStaticPgn( chess_spider.params.pgn_url );
		return;
	}

	// pgn as GET - return since callback will parse
	// todo: do not think this is true
	else if( /pgn=/.test(document.location.href) ) {
		nonblockAlert( document.location.href );
		return;
	}

	// todo: pgn as cookie - do as per GET

	// parse if we have pgn
	if( chess_spider.params.pgn ) chess_spider.Game.parsePgn();

	// if nothing to parse, we are ready for user
	else chess_spider.state.ready = true;

	chess_spider.state.initialized = true;

	// closure methods - - - - - - - - - - - - - - - - - - - -

	// run after onload
	function onloadInit() {

		// already run
		if( chess_spider.state.onloadInitialized ) return;

		// draw basic stuff
		chess_spider.FixedBoard.initAll();
		chess_spider.MoveList.initAll();

		// show the game
		chess_spider.tasks.postLoadPgn();

		// see if anything from local
		if( chess_spider.local.init ) chess_spider.local.init();

		// reposition - might be done later as well
		reposition();

		// done
		chess_spider.state.onloadInitialized = true;
	}

	// resize / re-position
	function reposition() {

		// center each fixed within its parent
		chess_spider.FixedBoard.fixedboards().forEach( function(fb) { fb.reposition() } );

		// movelist
		chess_spider.MoveList.movelists().forEach( function(ml) { ml.reposition() } );
	}

	// support functions - - - - - - - - - - - - - - - - - - - -

	// load static pgn
	function loadStaticPgn( url ) {
		var xhr = new XMLHttpRequest();
		xhr.open("GET",url,false);
		xhr.overrideMimeType( "text/html" );
		xhr.onreadystatechange=function() {
			console.log( 'xhr answer' );
			if( xhr.readyState==4 ) {
				// get pgn
				chess_spider.params.pgn_url = url;
				chess_spider.params.pgn = xhr.responseText;
				console.log( 'loadStaticPgn result: ' + chess_spider.params.pgn.substr(0,20) + '...' );
				if( chess_spider.params.pgn ) chess_spider.Game.parsePgn();
			}
			// todo: error condition
		}
		console.log( 'xhr for pgn_url: ' + url );
		xhr.setRequestHeader('Accept','message/x-jl-formresult');
		xhr.send(null);
	}
}

// run after pgn loaded - return success
chess_spider.tasks.postLoadPgn = function( game_idx ) {

	// if no games, nothing to do
	if( !chess_spider.state.game_arr.length ) return false;

	// make sure game_idx ok
	game_idx = (game_idx && chess_spider.state.game_arr[game_idx]) ? game_idx : 0;

	// if we have games, display
	chess_spider.state.game_arr[game_idx].display( chess_spider.params.movelist_dflt, chess_spider.params.fixedboard_dflt );

	// redisplay fixedboards
	chess_spider.FixedBoard.resetAllOptions();

	return true;
}


// load new pgn
// note: p_this can be dom or url
chess_spider.tasks.loadPgnSubmit = function(p_this) {

	// if string
	if( typeof p_this == 'string' ) {
		var input = null;
		var url = p_this;
	}

	// get input
	else {
		var input = p_this.previousSibling;
		while( input.tagName != 'INPUT' ) input = input.previousSibling;
		var url = input.value;
	}

	// empty url
	if( url.length < 1 ) {
		nonblockAlert( 'must enter URL' );
		if( input ) input.focus();
		return false;
	}

	// prefix with http
	if( !/^(http|shttp|file):/.test(url) ) url = 'http://' + url;
	if( input && !confirm( "Loading PGN from "+url+"\nIs this right?" ) ) return false;

	new chess_spider.Message( 'loadpgn', { 'url': url }, null, function( message ) {

		// success
		console.log( 'load pgn success' );
		chess_spider.params.pgn_url = url;
		chess_spider.params.pgn = message.result.pgn;

		// if parse and load correctly, set ready
		if( chess_spider.Game.parsePgn() && chess_spider.tasks.postLoadPgn() ) {
			chess_spider.state.ready = true;
		}

	}, function( message ) {

		// failure
		nonblockAlert( message.result.message + '\nurl: ' + url );
		if( input ) input.focus();
	} );

	return false;
}

// save button pushed - this will act as a closure, whose name space is in chess_spider.closure.save, for all save operations
chess_spider.tasks.save = function( p_this ) {

	// if div already created, done
	if( document.getElementById('cs__save') ) return;

	// create div in which to save
	var div = document.createElement('DIV');
	div.className = 'cs__dialogue';
	var source_arr = chess_spider.stores.source_arr();

	// todo: no game, no user data
	// no means to save data
	if( !source_arr.length ) {
		var buf = "Unable to save work locally or to chess-spider.com on the net<br/>"
			+ "Please Login or Join <a href='wwww.chess-spider.com'>chess_spider.com</a><br/>"
			+ "<button style='width:80%;' >Cancel Save</button>";
		div.innerHTML = buf;
		div.getElementsByTagName('button')[0].addEventListener('click',cancel,true);
	}
	// saving data - source and title
	else {
		var buf = "<form><table><tr><th>Save:</th><td> ";
		for( var source = source_arr.pop(); source; source = source_arr.pop() ) {
			buf += "<input type='radio' name='cs__save_source' value='"+source+"' > "+chess_spider.stores[source].description+" ";
		}
		buf += "</td></tr><tr><th>URL:</th><td><input style='width:60ex;' name='cs__save_url' value='"+get_url()+"' /></td></tr>"
		    +  "<tr><th>Title:</th><td><input style='width:60ex;' name='cs__save_title' value='"+get_title()+"' /></td></tr>"
		    +  "<tr><td colspan=2><button >Save</button> &nbsp; <button >Cancel</button></td></tr></table></form>";
		div.innerHTML = buf;
		div.getElementsByTagName('button')[0].addEventListener('click',save,true);
		div.getElementsByTagName('button')[0].addEventListener('click',cancel,true);
	}
	document.body.insertBefore( div, document.body.firstChild );
	//-div.style.top = (p_this.clientTop+p_this.clientHeight+5) + 'px';
	//-div.style.right = (p_this.clientLeft-50) + 'px';
	
	// get title for saving
	get_title = function() {
		if( chess_spider.state.game_arr[0].headers['Title'] ) return chess_spider.state.game_arr[0].headers['Title'];
		return get_url();
	}
	// get url for saving
	get_url = function() {
		var url = chess_spider.params.pgn_url;
		if( !url && chess_spider.state.game_arr[0].headers['Source'] ) url = chess_spider.state.game_arr[0].headers['Source'].value;
		if( url && url.indexOf(':')>0) url = url.replace(/^.*:\/\//,'');
		return url;
	}

	// save save
	function save() {

		// get div
		var form = div.getElementsByTagName('FORM')[0];
		if( !form ) alert( 'cannot get form' );

		// get source
		var source = cs__getRadio( form, 'cs__save_source' );
		var url = (form.cs__save_url.value) ? form.cs__save_url.value.purify() : null;
		var title = (form.cs__save_title.value) ? form.cs__save_title.value.purify() : null;
		//-alert( 'source='+source+", title="+title);
		if( !source || !title ) {
			alert( "Must specify Title and How you wish to Save" );
			form.cs__save_title.focus();
			return false;
		}

		// gather the data
		var data = JSON.stringify(chess_spider.tasks.gatherUserData());

		// save in localStore
		chess_spider.stores[source].save( url, title, data );
		
		// done
		cancel();
	}

	// save cancel
	function cancel() {

		// if div not created, done
		document.body.removeChild( div );

		var e = window.event;
		if( !e ) return;
		e.stopPropagation();
		e.preventDefault();

	}
}

// save save
chess_spider.tasks.restorePullList = function( url ) {

	// fix url - assume two slashes after colon
	if( url.indexOf(':') ) url = url.match(/\/\/(.*)/)[1];

	// var for pull return funcs
	var source_arr = chess_spider.stores.source_arr();
	var wait_ct = source_arr.length;
	var result_arr = [];

	// nothing to restore
	if( wait_ct == 0 ) {
		chess_spider.state.ready = true;
		return false;
	}

	// if not loaded
	if( !document.body ) {
		wait_ct++;
		window.addEventListener('load',onload,true);
	}

	// function to get onload
	function onload() {
		wait_ct--;
		console.log( 'onload callback: result_arr.length='+result_arr.length+", wait_ct="+wait_ct );
		if( wait_ct == 0 ) present_pulled_list();
	}

	// pull list from each source
	for( var source = source_arr.pop(); source; source = source_arr.pop() ) {
		// pull stores
		chess_spider.stores[source].pullList( url, function(src,arr) {
			result_arr = result_arr.concat( arr );
			wait_ct--;
			console.log( src + ' callback: result_arr.length='+result_arr.length+", wait_ct="+wait_ct );
			if( wait_ct == 0 ) present_pulled_list();
		} );
	}

	function present_pulled_list() {

		// no list
		if( result_arr.length == 0 ) return;
		
		// single
		else if( result_arr.length == 1 ) {
			if( confirm( "Restore from "+result_arr[0].source+" entitled \"" + result_arr[0].title + "\"?" ) ) {
				pull_save( result_arr[0] );
			}
			else return;	
		}

		// muliple
		else if( result_arr.length > 1 ) {

			// display
			var div = document.createElement('DIV');
			div.className = 'cs__dialogue';
			var html = "<form><table class='cs__list' ><tr><th></th><th>Title</th><th>Source</th><th>Date</th><th>Count</th></tr>";
			for( var i=0; i<result_arr.length; i++ ) {
				html += "<tr>"
					+"<td><input type='radio' name='cs__pull' value='"+i+"' /></td>"
					+"<td class='l'>"+result_arr[i].title+"</td>"
					+"<td>"+result_arr[i].source+"</td>"
					+"<td>"+new Date(result_arr[i].access_ts).format()+"</td>"
					//-+"<td>"+'2011/01/02 14:34'+"</td>"
					+"<td class='r' >"+result_arr[i].access_ct+"</td>"
				+"</tr>";
			}
			html += "<tr><td colspan='5' style='border-top-style: none; padding: 0px;' >"
				+"<button >Restore from Saved Source</button>"
				+" &nbsp; "
				+"<button >Cancel - Do NOT Restore</button>"
				+"</tr></table></form>";
			div.innerHTML = html; 
			div.getElementsByTagName('button')[0].addEventListener('click',pull_save,true);
			div.getElementsByTagName('button')[1].addEventListener('click',pull_cancel,true);
			document.body.insertBefore( div, document.body.firstChild );
			return;
		}
	}

	// cancel selection
	function pull_cancel() {

		var e = window.event;
		if( !e ) return;
		e.stopPropagation();
		e.preventDefault();

		// get rid of 
		var node = e.target.ancestorByClassName('cs__dialogue');
		if( node && node.parentNode ) node.parentNode.removeChild( node );
	}

	// pull the saved row that will be restored to page
	function pull_save( row ) {

		var e = window.event;

		// if no row, then get from
		if( e ) {

			// get form
			var form = e.target.ancestorByTagName('FORM');
			var idx = cs__getRadio( form, 'cs__pull' );

			// no radio button checked
			if( idx === null ) {
				e.stopPropagation();
				e.preventDefault();
				alert( 'No Save Selected to Restore' );
				return;
			}

			// here's the row we're working on
			row = result_arr[idx];
			console.log( 'row: idx=' + idx +', source='+row.source+', title='+row.title );

			// get rid of list
			pull_cancel();
		}

		// from source
		chess_spider.stores[row.source].pull( row, pull_restore );
		
		// rid interface
		pull_cancel();
	}

	// restore the pulled row
	function pull_restore( src, row ) {

		// console.log( 'pull_restore from '+src+': '+row );

		// get data into object from json string
		var data = JSON.parse(row);

		// go through each game
		for( var i=0; i<data.game_arr.length; i++ ) {

			// todo: make sure changes match the game
		
			// save restore moves 
			var game = chess_spider.state.game_arr[i];
			game.restoreMoves = data.game_arr[i].moves;
			
			// headers
			for( h in data.game_arr[i].headers )
			if( typeof data.game_arr[i].headers[h] == 'object' ) {
				chess_spider.state.game_arr[i].headers[h] = data.game_arr[i].headers[h];
			}
		}

		// let the games restore moves
		// todo: is this redundant?
		chess_spider.Game.restoreAll();

		// now ready for user
		chess_spider.state.ready = true;
	}

	return false;
}

// gather user data into an object
chess_spider.tasks.gatherUserData = function() {

	// init data object
	var data = { 'changes': 0, 'game_arr': [] };

	// collect from each game
	for( var i=0; i<chess_spider.state.game_arr.length; i++ ) {

		// init user data object for game
		data.game_arr[i] = { 'headers': {}, 'moves': {} };

		// pull out headers
		for( h in chess_spider.state.game_arr[i].headers )
		if( typeof chess_spider.state.game_arr[i].headers[h] == 'object' && chess_spider.state.game_arr[i].headers[h].mode != 'pgn' ) {
			data.game_arr[i].headers[h] = chess_spider.state.game_arr[i].headers[h];
			data.changes++;
		}

		// pull out moves
		var gregx = new RegExp( '^G' + i + 'B' );
		for( var move = chess_spider.state.game_arr[i].root_mv; move; move = move.nxt ) {
			if( move.mode == 'user' ) {
				data.game_arr[i].moves[move.id] = {
					'id': move.id,
					'move_no': move.move_no,
					'color': move.color,
					'move': move.move,
					'prv': (move.prv) ? move.prv.id : null,
					'pre_comment': move.pre_comment,
					'comment': move.comment };
				data.changes++;
			}
			else if( move.ucomment ) {
				data.game_arr[i].moves[move.id] = {
					'id': move.id,
					'move_no': move.move_no,
					'color': move.color,
					'move': move.move,
					'ucomment': move.ucomment };
				data.changes++;
			}
		}
	}

	return data;
}

// export button pushed
chess_spider.tasks.export = function( p_idx ) {

	// if div already created, done
	if( document.getElementById('cs__export') ) return;

	// create div in which to save
	var div = document.createElement('DIV');
	div.id = 'cs__export';

	// pull pgn
	var pgn = ( typeof p_idx != 'number' ) ? chess_spider.Game.writePgns() : chess_spider.state.game_arr[p_idx].writePgn();

	//-var exportLink = document.createElement('a');
	//-exportLink.setAttribute('href', 'data:application/x-chess-pgn;base64,' + window.btoa(pgn));
	//-exportLink.appendChild(document.createTextNode('Download PGN*'));
	//-div.appendChild(exportLink);

	var buf = ( ( typeof p_idx == 'number' ) ? '<b>'+chess_spider.state.game_arr[p_idx].title()+'</b><br/>' : '' )
		+ "<a href='data:application/x-chess-pgn;base64," + window.btoa(pgn) + "'>Download PGN*</a>"
		+ " &nbsp; <a href='cnp' onclick='return chess_spider.export_cnp()'>Cut and Paste</a> "
		+ " &nbsp; <a href='cancel' onclick='return chess_spider.export_cancel()'>Cancel Export</a>"
		+ "<hr />"
		+ "<span style='font-size:10px;'>* Download PGN uses advanced HTML5 techniques;<br/>"
	        + " &nbsp; your browser may not currently support this feature</span><br/>";

	div.innerHTML += buf;
	document.body.insertBefore( div, document.body.firstChild );

	// add scope funcs
	chess_spider.export_cancel = export_cancel;
	chess_spider.export_cnp = export_cnp;

	return false;

	function export_cancel() {

		// remove div from dom
		document.body.removeChild(div);

		// remove scope funcs (including this func?!?)
		delete chess_spider.export_cnp;
		delete chess_spider.export_cancel;

		return false;
	}

	function export_cnp() {
		// if already there, get rid of it
		if( div.getElementsByTagName('pre').length ) {
			div.removeChild(div.lastChild);
			div.removeChild(div.lastChild);
		}
		// put pgn there in pre
		else {
			var buf = "<hr/><div style='overflow:auto;'><pre>"+pgn+"</pre>"
				+ "<button onclick='chess_spider.export_cancel()' style='width:100%' >Close PGN</button></div>";
			div.innerHTML += buf;
		}

		return false;
	}
}

